package project_cmd

import (
	"context"
	"fmt"
	"time"

	"atomgit.com/openlinksaas/swarm_api_proxy/config"
	"atomgit.com/openlinksaas/swarm_api_proxy/utils"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/api/types/swarm"
	"github.com/spf13/cobra"
)

var addCmd = &cobra.Command{
	Use: "add",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return fmt.Errorf("need param [project id]")
		}
		return nil
	},
	RunE: runAdd,
}

func runAdd(cmd *cobra.Command, args []string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if cfgPath == nil {
		return fmt.Errorf("miss config")
	}
	cfg, err := config.LoadProxyConfig(*cfgPath)
	if err != nil {
		return err
	}
	c, err := utils.GetDockerClient(cfg.ServerUrl, cfg.CertPath)
	if err != nil {
		return err
	}
	defer c.Close()

	filter := filters.NewArgs()
	filter.Add("name", config.PROJECT_CONFIG_KEY+args[0])
	tmpCfgItemList, err := c.ConfigList(ctx, types.ConfigListOptions{
		Filters: filter,
	})
	if err != nil {
		return err
	}

	cfgItemList := []swarm.Config{}
	for _, cfgItem := range tmpCfgItemList {
		if cfgItem.Spec.Name == config.PROJECT_CONFIG_KEY+args[0] {
			cfgItemList = append(cfgItemList, cfgItem)
		}
	}

	if len(cfgItemList) > 0 {
		fmt.Println("project", args[0], "allready exist")
		return nil
	}
	_, err = c.ConfigCreate(ctx, swarm.ConfigSpec{
		Annotations: swarm.Annotations{
			Name: config.PROJECT_CONFIG_KEY + args[0],
			Labels: map[string]string{
				config.PROJECT_CONFIG_KEY: "1",
			},
		},
		Data: []byte(args[0]),
	})
	if err != nil {
		return err
	}
	fmt.Println("add project", args[0], "success")
	return nil
}
